package Customer;

use Moose;
use feature qw(switch);
## no cirtic (Perl::Critic::Policy::CodeLayout::ProhibitTrailingWhitespace)

has '_name' => (
    isa => 'Str',
    is => 'ro',
);

has '_rentals' => (
    is => 'bare',
    builder => 'new_rentals',
);

sub new_rentals {
    return ();
}

sub add_rental {
    my $self = shift;

    # push (@$self->{ _rentals }, shift); 这样会有语法错误
    push @{ $self->{ _rentals } }, shift;
    return 0;
}

sub statement {
    my $self = shift;
    my $total_amount = 0;
    my $fre_rental_points = 0;
    my $rentals = $self->{ _rentals };
    my $result = "Rental Record for $self->{ _name }\n";

    foreach my $rental (@{ $rentals }) {
        my $movie_name = $rental->get_movie()->get_title();
        $result .= "\t$movie_name\n";

        my $this_amount = amount_for($rental);

        $fre_rental_points++;
        if ($rental->get_movie()->get_price_code() == 1 && $rental->get_days_rented() > 1) {
            $fre_rental_points++;
        }
        $result .= "$this_amount\n";
        $total_amount += $this_amount;
    }

    $result .= "Amount owed is $total_amount\n";
    $result .= "You earned $fre_rental_points\n";

    return $result;
}

sub amount_for {
    my $rental = shift;
    my $result = 0;
    given ($rental->get_movie()->get_price_code()) {
        when(0) {
            $result = 2;
            if ($rental->get_days_rented() > 2) {
                $result += ($rental->get_days_rented() - 2) * 1;
            }
        }
        when(1) { $result = $rental->get_days_rented() * 3; }
        when(2) {
            $result = 1;
            if ($rental->get_days_rented() > 3) {
                $result += ($rental->get_days_rented() - 3) * 1;
            }
        }
    }
    return $result;
}

1;